package com.home.security.browser.auth.service.impl;

import com.home.common.utils.string.StringUtils;
import com.home.security.browser.auth.entity.SysAuthMenu;
import com.home.security.browser.auth.entity.SysAuthRole;
import com.home.security.browser.auth.mapper.AuthMapper;
import com.home.security.browser.auth.service.AuthService;
import com.home.common.model.CurrentUser;
import com.home.security.core.constants.UserTypeConstant;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Description: 当前登录用户
 * Created by 王大宸 on 2020-11-12 15:10
 * Created with IntelliJ IDEA.
 */
@Service
public class AuthServiceImpl implements AuthService {
    private static final Logger logger = LoggerFactory.getLogger(AuthServiceImpl.class);
    @Autowired
    private AuthMapper authMapper;

    /***
     * 功能说明：登录查询
     *
     * @author 王大宸
     * @date 2020/11/14 2:15
     * @param account  登录账号
     * @param client   登录客户端
     * @return com.home.common.framework.core.base.entity.CurrentUser
     */
    @Override
    public CurrentUser login(String account, String client) {
        if (StringUtils.isEmpty(account)) {
            logger.error("登录账号为空......");
            throw new UnknownAccountException();
        }
        CurrentUser sysUser = authMapper.getByAccount(account);
        if (null == sysUser) {
            logger.error("登录账号: " + account + "  找不到登录用户");
            throw new UnknownAccountException();
        }
        sysUser.setClientId(client);
        if (null == sysUser.getStatus()
                || "2".equals(sysUser.getStatus())
                || "0".equals(sysUser.getStatus())) {
//            logger.error("登录账号: " + username + "  已被冻结，冻结状态为: " + sysUser.getStatus());
//            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, sysUser.getName(), client,
//                    Constants.LOGIN_FAIL, MessageUtils.message(I18nMessages.USER_BLOCKED)));
            throw new LockedAccountException();
        }

        // 删除之前的会话,保证一个账号只有一个人在线
//        SysUserOnline session = new SysUserOnline();
//        session.setLoginName(sysUser.getUsername());
//        sysUserOnlineMapper.delete(session);

        // 在线用户入库
//        session = new SysUserOnline();
//        session.setId(EntityUtils.getId());
//        session.setLoginName(username);
//        session.setCreateTime(LocalDateTime.now());
//        session.setCreateUser(sysUser.getName());
//        session.setCreateUserId(sysUser.getId());
//        session.setStatus(OnlineStatusEnum.on_line);
//        session.setClientId(client);
//        AsyncManager.me().execute(AsyncFactory.syncSessionToDb(session));

        // 登录日志
//        AsyncManager.me().execute(
//                AsyncFactory.recordLogininfor(username,
//                        sysUser.getName(),
//                        client,
//                        Constants.LOGIN_SUCCESS,
//                        MessageUtils.message(I18nMessages.USER_LOGIN_SUCCESS)));
        return sysUser;
    }

    /***
     * 功能说明：根据登录用户信息,查询用户角色
     *
     * @author 王大宸
     * @date 2020/11/14 2:29
     * @param userId  用户id
     * @return java.util.List<com.home.security.auth.entity.SysAuthRole>
     */
    @Override
    public List<SysAuthRole> getRoleByUser(String userId) {
        return authMapper.getRoleByUser(userId);
    }

    /***
     * 功能说明：根据用户id,查询菜单
     *
     * @author 王大宸
     * @date 2020/11/14 2:30
     * @param userId 用户id
     * @return java.util.List<com.home.security.auth.entity.SysAuthMenu>
     */
    @Override
    public List<SysAuthMenu> getMenuByUser(String userId) {
        return authMapper.getMenuByUser(userId);
    }

    /***
     * 功能说明：根据用户信息获取用户菜单
     *
     * @author 王大宸
     * @date 2020/11/14 11:38
     * @param appCode    应用编码
     * @param userType   用户类型
     * @param userId     用户id
     * @return java.util.List<com.home.security.auth.entity.SysAuthMenu>
     */
    @Override
    public List<SysAuthMenu> getUserMenu(String appCode, String userType, String userId) {
        if (userType.equals(UserTypeConstant.SUPER_ADMINISTRATOR + "")) {
            return getMenuAll(appCode);
        } else {
            return getChildrenMenu(appCode, userId, "0");
        }
    }

    /***
     * 功能说明：获取用户权限
     *
     * @author 王大宸
     * @date 2020/12/15 10:08
     * @param appCode   应用编码
     * @param userType  用户类型
     * @param userId    用户id
     * @return java.lang.String
     */
    @Override
    public String getUserPerms(String appCode, String userType, String userId) {
        List<String> perms = null;
        if (userType.equals(UserTypeConstant.SUPER_ADMINISTRATOR + "")) {
            perms = authMapper.getPermsAll();
        } else {
            perms = authMapper.getPermsByUser(userId);
        }
        StringBuffer sb = new StringBuffer();
        for (String perm : perms) {
            sb.append(perm).append(",");
        }
        return sb.toString();
    }


    /***
     * 功能说明：用户获取菜单
     *
     * @author 王大宸
     * @date 2020/11/14 11:40
     * @param pid      上级菜单id
     * @param userId   用户id
     * @param haveButton   1-包含按钮;0-不包含按钮
     * @return java.util.List<com.home.security.auth.entity.SysAuthMenu>
     */
    private List<SysAuthMenu> getChildrenMenu(String pid, String userId, String haveButton) {
        List<SysAuthMenu> menus = authMapper.getAuthMenuByUser(pid, userId, haveButton);
        for (SysAuthMenu sysMenu : menus) {
            List<SysAuthMenu> children = getChildrenMenu(sysMenu.getId(), userId, haveButton);
            if (0 == children.size()) {
                continue;
            }
            sysMenu.setChildren(children);
        }
        return menus;
    }

    /***
     * 功能说明：获取所有的菜单
     *
     * @author 王大宸
     * @date 2020/12/15 10:13
     * @param pid
     * @param userId
     * @return java.util.List<com.home.security.browser.auth.entity.SysAuthMenu>
     */
//    private List<SysAuthMenu> getUserPerms(String pid, String userId) {
//        List<SysAuthMenu> menus = authMapper.getAuthMenuByUser(pid, userId);
//        for (SysAuthMenu sysMenu : menus) {
//            List<SysAuthMenu> children = getChildrenMenu(sysMenu.getId(), userId);
//            if (0 == children.size()) {
//                continue;
//            }
//            sysMenu.setChildren(children);
//        }
//        return menus;
//    }

    /***
     * 功能说明：管理员获取所有菜单
     *
     * @author 王大宸
     * @date 2020/11/14 11:40
     * @param pid  上级菜单id
     * @return java.util.List<com.home.security.auth.entity.SysAuthMenu>
     */
    private List<SysAuthMenu> getMenuAll(String pid) {
        List<SysAuthMenu> menus = authMapper.getMenuAll(pid);
        for (SysAuthMenu sysMenu : menus) {
            List<SysAuthMenu> children = getMenuAll(sysMenu.getId());
            if (0 == children.size()) {
                continue;
            }
            sysMenu.setChildren(children);
        }
        return menus;
    }
}
